#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2018/4/13 17:14
# @Author  : simple0426
# @Email   : istyle.simple@gmail.com
# @File    : pexpect_demo.py
# @Software: PyCharm

from pexpect import pxssh
import getpass
import pexpect

# ssh使用范例【官方范例微修改】
# try:
#     s = pxssh.pxssh()
#     hostname = input('hostname: ')
#     username = input('username: ')
#     password = getpass.getpass('password: ')
#     s.login(hostname, username, password)
#     with open('log.txt', 'wb') as f:
#         s.logfile = f
#         s.sendline('uptime')  # run a command
#         s.prompt()  # match the prompt
#         print(s.before)  # print everything before the prompt.
#         s.sendline('ls -l')
#         s.prompt()
#         print(s.before)
#         s.sendline('df')
#         s.prompt()
#         print(s.before)
#         s.logout()
# except pxssh.TIMEOUT:
#     print("expect timeout")
# except pxssh.ExceptionPxssh as e:
#     print("pxssh failed on login.")
#     print(e)

# scp使用范例
filename = input('filename:').strip()
password = getpass.getpass('password:')
fout = open('mylog.txt','a+', encoding='utf-8')
child = pexpect.spawn('scp', [filename,'python@api.unforget.cn:~/'], encoding='utf-8')
child.logfile = fout
try:
    child.expect('(yes/no)?')
    child.sendline('yes')
    child.expect('(?i)password:')
    child.sendline(password)
    child.expect(pexpect.EOF)
    fout.close()
except pexpect.exceptions.TIMEOUT:
    print('expect TIMEOUT')
